package com.logos.cartoon.service.impl;

import com.alibaba.fastjson.JSON;
import com.logos.cartoon.constant.LoginConstant;
import com.logos.cartoon.constant.RegisterConstant;
import com.logos.cartoon.converter.AuthUserConverter;
import com.logos.cartoon.entity.AuthUser;
import com.logos.cartoon.entity.CharacterInfo;
import com.logos.cartoon.exception.LoginException;
import com.logos.cartoon.mapper.AuthUserMapper;
import com.logos.cartoon.mapper.CharacterInfoMapper;
import com.logos.cartoon.redis.RedisUtil;
import com.logos.cartoon.req.AuthUserReq;
import com.logos.cartoon.resp.AuthUserResp;
import com.logos.cartoon.resp.CharacterInfoResp;
import com.logos.cartoon.service.AuthUserService;
import com.logos.cartoon.utils.JwtTool;
import com.logos.cartoon.utils.LoginUtil;
import com.logos.cartoon.utils.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 用户表(AuthUser)表服务实现类
 *
 * @author rose
 * @since 2025-03-17 20:06:11
 */
@Service("authUserService")
@Slf4j
public class AuthUserServiceImpl implements AuthUserService {
    @Resource
    private AuthUserMapper authUserMapper;

    @Resource
    private CharacterInfoMapper characterInfoMapper;

    @Resource
    private JwtTool jwtTool;

    @Resource
    private LoginUtil loginUtil;

    @Resource
    private RedisUtil redisUtil;

    public static final String pattern = "character:liked:detail:*:";

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public AuthUser queryById(Long id) {
        return this.authUserMapper.queryById(id);
    }

    @Override
    public String login(AuthUserReq authUserReq) {
        if (log.isInfoEnabled()) {
            log.info("AuthUserService.java.login.authUserRequest:{}", JSON.toJSONString(authUserReq));
        }
        // 查询是否存在当前用户
        AuthUser authUser = new AuthUser();
        authUser.setPhone(Md5Utils.encode(authUserReq.getPhone()));
        authUser = authUserMapper.queryByCondition(authUser);
        if (authUser == null) {
            throw new LoginException(LoginConstant.USER_NOEXIST);
        }
        authUser.setPassword(Md5Utils.encode(authUserReq.getPassword()));
        authUser = authUserMapper.queryByCondition(authUser);
        if (authUser == null) {
            throw new LoginException(LoginConstant.PASSWORD_ERROR);
        }
        String token = jwtTool.createToken(authUser.getPhone(), Duration.ofDays(1L));
        return token;
    }

    @Override
    public String register(AuthUserReq authUserReq) {
        if (log.isInfoEnabled()) {
            log.info("AuthUserService.java.login.authUserRequest:{}", JSON.toJSONString(authUserReq));
        }
        // 查询是否存在当前用户
        AuthUser authUser = new AuthUser();
        authUser.setPhone(Md5Utils.encode(authUserReq.getPhone()));
        authUser = authUserMapper.queryByCondition(authUser);
        if (authUser != null) {
            throw new LoginException(RegisterConstant.PHONE_EXIST);
        }
        authUser = AuthUserConverter.INSTANCE.convertReqToEntity(authUserReq);
        authUser.setPassword(Md5Utils.encode(authUserReq.getPassword()));
        authUser.setPhone(Md5Utils.encode(authUserReq.getPhone()));
        authUser.setNickName(authUserReq.getNickName());
        int count = authUserMapper.insert(authUser);
        if (count <= 0) {
            throw new LoginException(RegisterConstant.REGISTER_ERROR);
        }
        String token = jwtTool.createToken(authUser.getPhone(), Duration.ofDays(1L));
        return token;
    }

    @Override
    public AuthUser getUserInfo(String loginPhone) {
        AuthUser authUser = new AuthUser();
        authUser.setPhone(loginPhone);
        authUser = authUserMapper.queryByCondition(authUser);
        return authUser;
    }

    @Override
    public AuthUserResp queryMy(String loginPhone) {
        // 查询个人信息
        AuthUser authUser = new AuthUser();
        authUser.setPhone(loginPhone);
        authUser = authUserMapper.queryByCondition(authUser);
        AuthUserResp authUserResp = AuthUserConverter.INSTANCE.convertEntityToResp(authUser);
        // 查询关于该用户的点赞个数

        authUserResp.setLikeCount(10);
        List<CharacterInfoResp> characterInfoRespList = getCharacterInfoRespList(String.valueOf(authUser.getId()));
        if (characterInfoRespList != null && characterInfoRespList.size() > 0) {
            authUserResp.setLikeCount(characterInfoRespList.size());
        }else{
            authUserResp.setLikeCount(0);
        }
        // 查询关于该用户的收藏列表

        authUserResp.setCollectCount(10);
        // 查询关于该用户的浏览记录
        return authUserResp;
    }

    /**
     * 新增数据
     *
     * @param authUser 实例对象
     * @return 实例对象
     */
    @Override
    public AuthUser insert(AuthUser authUser) {
        this.authUserMapper.insert(authUser);
        return authUser;
    }

    @Override
    public Boolean update(AuthUserReq authUserReq) {
        if (log.isInfoEnabled()) {
            log.info("AuthUserService.java.update.authUserRequest:{}", JSON.toJSONString(authUserReq));
        }
        AuthUser authUser = AuthUserConverter.INSTANCE.convertReqToEntity(authUserReq);
        Integer count = authUserMapper.updateByPhone(authUser);
        if (count <= 0) {
            return false;
        }
        return true;
    }

    @Override
    public List<CharacterInfoResp> queryMyLike(String loginPhone) {
        String id = loginUtil.getId();
        return getCharacterInfoRespList(id);
    }

    private List<CharacterInfoResp> getCharacterInfoRespList(String id) {
        // TODO 这里先去redis中查，等实现mq消息发送，将redis数据写入数据库中，再在数据库中查
        Set<String> keys = redisUtil.scanKeys(pattern + id);
        log.info("queryMyLike.keys:{}",keys);
        List<Integer> charIdList = new ArrayList<>();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                Integer charId = Integer.valueOf(key.split(":")[3]);
                charIdList.add(charId);
            }
        }
        log.info("queryMyLike.charIdList:{}",charIdList);
        List<CharacterInfoResp> characterInfoList = new ArrayList<>();
        // 去数据库查询角色列表
        if (charIdList != null && charIdList.size() > 0) {
            characterInfoList = characterInfoMapper.queryByIds(charIdList);
            log.info("queryMyLike.characterInfoList:{}",characterInfoList);
        }
        return characterInfoList;
    }
}
